import { cloneElement, HTMLAttributes, isValidElement, useEffect, useState, type FC } from 'react';
import { isForwardRef, isFragment } from 'react-is';
import classNames from 'classnames';
import {
  autoUpdate,
  flip,
  offset,
  type Placement,
  shift,
  useFloating,
  useHover,
  useInteractions,
  useClick,
  useFocus,
} from '@floating-ui/react';
import { popupDefaultProps } from './defaultProps';
import type { PopupOptions } from './type';
import { useUpdateEffect } from 'react-use';
import { SizeEnum } from '../common';

export interface PopupProps extends PopupOptions, HTMLAttributes<HTMLDivElement> {}

const Popup: FC<PopupProps> = (props) => {
  const {
    className,
    header,
    content,
    duration,
    delay,
    position,
    size,
    basic,
    wide,
    fluid,
    flowing,
    inverted,
    trigger,
    children,
    style,
    ...popupProps
  } = props;
  const [open, setOpen] = useState(false);
  const [inTransition, setInTransition] = useState(false);
  const [css, setCss] = useState<string>();
  const [styled, setStyled] = useState(style);
  const [pos, setPos] = useState<string>();

  const getOffset = (m: number, n: number) => {
    return position?.startsWith('top') || position?.startsWith('left') ? m : n;
  };

  const sizeOffset: { [key in SizeEnum]: number } = {
    mini: getOffset(4, 0),
    tiny: getOffset(5, -1),
    small: getOffset(6, -2),
    medium: getOffset(7, -3),
    large: getOffset(8, -4),
    big: getOffset(9, -5),
    huge: getOffset(10, -6),
    massive: getOffset(11, -7),
  };

  const { floating, reference, context, placement, strategy, x, y } = useFloating({
    open,
    onOpenChange: setOpen,
    placement: position,
    middleware: [offset(size ? sizeOffset[size] : getOffset(7, -3)), flip(), shift()],
    whileElementsMounted: autoUpdate,
  });

  const hover = useHover(context, { enabled: trigger === 'hover', move: false, delay });
  const click = useClick(context, { enabled: trigger === 'click' });
  const focus = useFocus(context, { enabled: trigger === 'focus', keyboardOnly: false });

  const { getReferenceProps, getFloatingProps } = useInteractions([hover, click, focus]);

  const node = isValidElement(children) && !isFragment(children) ? children : <span>{children}</span>;

  const refKey = typeof node.type === 'function' ? (isForwardRef(node) ? 'ref' : 'forwardedRef') : 'ref';

  useUpdateEffect(() => {
    setInTransition(true);
  }, [open]);

  useEffect(() => {
    if (inTransition) {
      setCss(`animating transition scale ${open ? 'in' : 'out'}`);
      setStyled({ ...style, animationDuration: `${duration}ms` });
      setTimeout(() => {
        setInTransition(false);
        setStyled({ ...style });
      }, duration);
    } else {
      setCss(open ? 'transition visible' : undefined);
    }
  }, [inTransition]);

  useEffect(() => {
    const pos: { [key in Placement]: string } = {
      top: 'top center',
      right: 'right center',
      bottom: 'bottom center',
      left: 'left center',
      'top-start': 'top left',
      'top-end': 'top right',
      'right-start': 'right center',
      'right-end': 'right center',
      'bottom-start': 'bottom left',
      'bottom-end': 'bottom right',
      'left-start': 'left center',
      'left-end': 'left center',
    };

    setPos(pos[placement]);
  }, [placement]);

  return (
    <>
      {cloneElement(node, {
        ...node.props,
        [refKey]: reference,
        ...getReferenceProps(),
      })}
      <div
        ref={floating}
        className={classNames(
          'ui',
          size,
          pos,
          { basic, fluid, flowing, inverted },
          wide,
          { wide },
          'popup',
          css,
          className,
        )}
        style={{
          ...styled,
          position: strategy,
          top: y ?? 0,
          right: 'auto',
          bottom: 'auto',
          left: x ?? 0,
          width: 'max-content',
        }}
        {...getFloatingProps()}
        {...popupProps}
      >
        {header ? (
          <>
            <div className="header">{header}</div>
            <div className="content">{content}</div>
          </>
        ) : (
          content
        )}
      </div>
    </>
  );
};

Popup.displayName = 'Popup';
Popup.defaultProps = popupDefaultProps;

export default Popup;
